const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const async = require("async");

const pageQuery = function (
  page = 1,
  pageSize = 10,
  Model,
  populate,
  queryParams,
  filterField,
  sortParams,
  callback
) {
  const start = (page - 1) * pageSize;
  const $page = {
    pageNumber: page,
  };
  async.parallel(
    {
      count: function (done) {
        // 查询数量
        Model.count(queryParams).exec(function (err, count) {
          done(err, count);
        });
      },
      records: function (done) {
        // 查询一页的记录
        Model.find(queryParams, filterField)
          .skip(start)
          .limit(pageSize)
          .populate(populate)
          .sort(sortParams)
          .lean()
          .exec(function (err, doc) {
            done(err, doc);
          });
      },
    },
    function (err, results) {
      const count = results.count;
      $page.pageCount = (count - 1) / pageSize + 1;
      $page.results = results.records;
      $page.pageSize = pageSize;
      $page.count = count
      callback(err, $page);
    }
  );
};

function getRecorders(page, pageSize, Model, queryParams, filterField) {
  return new Promise((resolve, reject) => {
    pageQuery(page, pageSize, Model, "", queryParams, filterField, "", (error, $page) => {
      if (error) {
        reject(error);
        return;
      }
      resolve($page);
    });
  });
}

module.exports = {
  pageQuery: pageQuery,
  getRecorders,
};
